package com.dal.guava.aspect;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.dal.guava.annotations.Limit;
import com.dal.guava.common.Result;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;


/**
 * @author jian
 */
@Aspect
@Component
public class LimitAspect {

    private static final Logger log = LoggerFactory.getLogger(LimitAspect.class);
    /**
     * 不同的接口，不同的流量控制
     * map的key为 ArtisanLimit.key
     */
    private final Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();


    @Around("@annotation(com.dal.guava.annotations.Limit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("请求拦截时间:[{}]", DateUtil.now());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //拿ArtisanLimit的注解
        Limit limit = method.getAnnotation(Limit.class);

        if (limit != null) {
            //获取限流标识key作用：不同的接口，不同的流量控制
            String limitKey = limit.key();
            if (StringUtils.isEmpty(limitKey)) {
                limitKey = method.getDeclaringClass().getName() + "." + method.getName();
            }

            log.info("令牌桶的容量为:[{}]", limitMap.size());
            //获取注解每秒加入桶中的token
            double limitNum = limit.permitsPerSecond();
            log.info("获取注解每秒加入桶中的token:[{}]", limitNum);
            //验证缓存是否有命中key
            RateLimiter rateLimiter = limitMap.computeIfAbsent(limitKey, k -> RateLimiter.create(limitNum));
            log.info("rateLimiter:[{}]", rateLimiter);
            // 拿令牌
            boolean acquire = rateLimiter.tryAcquire(limit.timeout(), limit.timeunit());
            // 拿不到命令，直接返回异常提示
            if (!acquire) {
                // 获取失败，返回限流信息
                log.warn("请求被限流，key={}, rate={} permits/sec",
                        limitKey, rateLimiter.getRate());
                this.responseFail(limit.message());
                return null;
            }else {
                // 获取成功，继续执行方法
                log.debug("令牌获取成功，key={}, rate={} permits/sec",
                        limitKey, rateLimiter.getRate());
                return joinPoint.proceed();
            }
        }
        return joinPoint.proceed();
    }


    /**
     * 直接向前端抛出异常
     *
     * @param msg 提示信息
     */
    private void responseFail(String msg) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print(JSONUtil.toJsonStr(Result.error(msg)));
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
    
